import { DownOutlined } from '@ant-design/icons'
import { Dropdown, Space, Button, Modal } from 'antd'
import React, { useState, useRef } from 'react'
import './index.less'
import ConfigForm from '../config-form'

// 视频器编辑配置
const adapterConfig = [
  { key: '1', name: '硬件', title: '硬件编辑', template: '设备代号' },
  { key: '2', name: '总线', title: '总线模板编辑',template: '模版名' },
  { key: '3', name: '协议', title: '普通协议编辑',template: '模版名' },
  { key: '4', name: '观察者', title: '观察者模板编辑', template: '模版名' },
  { key: '5', name: '共享', title: '共享模板编辑',template: '模版名' },
]

export function ConfigPanel() {
  const [modalState, setModalState] = useState({
    isOpen: false,
    config: {},
  })

  const [formValue, setFormValue] = useState({
    templateName: '',
    list: [],
  })


  const handleOpenModal = (event) => {
    let config = adapterConfig.find((item) => item.key === event.key)

    setFormValue({
      templateName: '',
      list: [],
    })
    setModalState({
      isOpen: true,
      config,
    })
  }

  const menuProps = {
    items: adapterConfig.map((item) => ({
      key: item.key,
      label: '增加' + item.name
    })),
    onClick: handleOpenModal,
  }

  const configFormRef = useRef(null)

  const handleOk = () => {
    configFormRef.current.validateFields().then((value) => {
      console.log(value)
      setModalState({
        ...modalState,
        isOpen: false,
      })
    }).catch(error => {
      console.error(error)
    })
  }

  const handleCancel = () => {
    setModalState({
      ...modalState,
      isOpen: false,
    })
  }

  return (
    <div className="config-pannel">
      <Space>
        <Dropdown menu={menuProps}>
          <Button type="primary">
            <Space>
              适配器
              <DownOutlined />
            </Space>
          </Button>
        </Dropdown>
      </Space>

      <Modal
        centered
        width={1300}
        title={modalState.config.title}
        open={modalState.isOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <ConfigForm ref={ configFormRef } config={modalState.config} value={formValue} onChange={setFormValue} />
      </Modal>
    </div>
  )
}
export default ConfigPanel
